package com.pkk.spring.cloud.config.nacos.factory;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.pkk.spring.cloud.config.nacos.config.NacosConfigProvider;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;

/**
 * @author peikunkun
 * @version V1.0
 * @date 2021-01-26 15:47
 **/
public class NacosConfigListenerFactory implements NacosConfigProvider {

  /**
   * nacos的配置容器
   */
  public static final Map<String, ConfigService> NACOS_CONFIGS = new ConcurrentHashMap<>();

  /**
   * 获取配置超时时间-毫秒
   */
  public static final long FETCH_NACOS_CONFIG_TIMEOUTMS_DEFAULT = 3000;


  /**
   * 获取配置身份id
   * 同一个配置需要保证身份id一致,否则可能导致重复创建配置
   * 例如: {svervletAddress+namespace}
   *
   * @param serverAddr
   * @param namespace
   * @return java.lang.String
   * @Param nacosProperties:配置信息
   * @author peikunkun
   * @date 2021/1/26 0026 下午 3:49
   * @since
   */
  @Override
  public String getConfigId(@NonNull String serverAddr, @NonNull String namespace) {
    return serverAddr.concat("-").concat(namespace);
  }


  /**
   * 获取全部配置
   *
   * @param configService
   * @param group
   * @param dataId
   * @return java.lang.String
   * @Param configService
   * @Param group
   * @Param dataId
   * @author peikunkun
   * @date 2021/1/26 0026 下午 4:26
   * @since
   */
  @Override
  public String getConfig(ConfigService configService, String group, String dataId) throws NacosException {
    return configService.getConfig(dataId, group, FETCH_NACOS_CONFIG_TIMEOUTMS_DEFAULT);
  }

  /**
   * 获取配置
   *
   * @param configId
   * @return com.alibaba.nacos.api.config.ConfigService
   * @Param configId {@see @getConfigId}
   * @author peikunkun
   * @date 2021/1/26 0026 下午 4:27
   * @since
   */
  @Override
  public ConfigService getConfig(String configId) throws NacosException {
    if (StringUtils.isBlank(configId)) {
      throw new IllegalArgumentException(
          "Failed to get nacos configuration, please check method NacosConfigListenerFactory.getConfigId()");
    }

    //从容器中取
    final ConfigService configServiceCache = NACOS_CONFIGS.get(configId);
    if (null != configServiceCache) {
      return configServiceCache;
    }

    final int i = configId.lastIndexOf("-");

    Properties properties = new Properties();
    properties.setProperty("serverAddr", configId.substring(0, i));
    properties.setProperty("namespace", configId.substring(i + 1, configId.length()));
    final ConfigService configService = NacosFactory.createConfigService(properties);
    if (null == configService) {
      throw new IllegalArgumentException("Failed to obtain nacos configuration, please check serverAddr and namespace");
    }
    NACOS_CONFIGS.put(configId, configService);
    return configService;
  }


}
